package com.hd.hdxgddcommon.web.wechatUtil;

import com.hd.hdxgddcommon.utils.MyX509TrustManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.URL;

/**
 * 实现发送https请求
 */

@Slf4j
public class RequestSSL {


    public static String sendHttps(String url, String method, String data) {

        BasicHttpClientConnectionManager connManager;
        connManager = new BasicHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
                        .build(),
                null,
                null,
                null
        );

        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connManager)
                .build();

        HttpResponse httpResponse;
        String rest = null;
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(WechatConstant.READ_TIMEOUT_MS).setConnectTimeout(WechatConstant.CONNECT_TIMEOUT_MS).build();
        try {
            if ("post".equals(method)) {
                HttpPost httpPost = new HttpPost(url);
                httpPost.setConfig(requestConfig);

                httpPost.addHeader("Content-Type", "text/xml");
                httpPost.addHeader("User-Agent", WechatConstant.USER_AGENT);
                StringEntity postEntity = new StringEntity(data, "UTF-8");
                httpPost.setEntity(postEntity);
                httpResponse = httpClient.execute(httpPost);
            } else {
                HttpGet httpGet = new HttpGet(url);
                httpGet.setConfig(requestConfig);
                httpGet.addHeader("Content-Type", "text/xml");
                httpGet.addHeader("User-Agent", WechatConstant.USER_AGENT);
                httpResponse = httpClient.execute(httpGet);
            }
            HttpEntity httpEntity = httpResponse.getEntity();
            rest = EntityUtils.toString(httpEntity, "UTF-8");
        } catch (IOException e) {
            log.error("发送https请求错误", e);
        }
        return rest;
    }


    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {

        String result = null;
        try {

            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());

            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);

            conn.setRequestMethod(requestMethod);


            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            conn.disconnect();
            result = buffer.toString();
        } catch (Exception e) {
            log.error("发送http请求错误", e);
        }
        return result;
    }

}
